using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
    
using SharePoint.ImportExport.Core;

namespace CodePlex.ExtractedDataReorganizer
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class MainApp : System.Windows.Forms.Form
    {
        private System.Windows.Forms.OpenFileDialog openFileDialog1;

        private string configFile="";

        private bool TemplateDataChanged = false;
        private bool DataChanged = false;
        HelperFunctions helperFunction = new HelperFunctions();
		// Node being dragged
		private TreeNode dragNode = null;
		
		// Temporary drop node for selection
		private TreeNode tempDropNode = null;

		// Timer for scrolling
		private Timer timer = new Timer();

		private Import importStructure=new Import();
        private ListOfContentTypes templates = new ListOfContentTypes();
		private System.Windows.Forms.ImageList imageListTreeView;
        private System.Windows.Forms.ImageList imageListDrag;
        private MenuStrip MainMenu;
        private ToolStripMenuItem fileToolStripMenuItem;
        private ToolStripMenuItem StructOpenMenuItem;
        private ToolStripMenuItem StructSaveMenuItem;
        private ToolStripMenuItem contentTypesToolStripMenuItem;
        private ToolStripMenuItem userToolStripMenuItem;
        private ToolStripMenuItem exitToolStripMenuItem;
        private TabControl tabControl1;
        private TabPage tabPage1;
        private TabPage tabPage2;
        private TextBox txtDataFile;
        private TreeView treeViewStruct;
        private TabPage tabPage3;
        private Button btnRename;
        private TextBox txtOldPattern;
        private Label label2;
        private TextBox txtNewPattern;
        private ToolStripMenuItem ContentTypesLoadMenuItem;
        private ToolStripMenuItem ContentTypesSaveMenuItem;
        private TextBox txtItemTypes;
        private TreeView treeViewContentTypes;
        private ContextMenuStrip ContentTypesContextMenu;
        private ToolStripMenuItem editContentTypeMenuItem;
        private ContextMenuStrip StructContextMenu;
        private ToolStripMenuItem RemoveStructMenuItem;
        private ToolStripMenuItem EditStructMenuItem;
        private ToolStripMenuItem removeContentTypeMenuItem;
        private TabPage tabPage4;
        private TextBox txtLog;
        private RadioButton rdDomain;
        private RadioButton rdUser;
        private Label label1;
        private Button btnReload;
        private ToolStripMenuItem populateToolStripMenuItem;
        private ToolStripMenuItem importToolStripMenuItem;
        private RichTextBox rtRenameLog;
        private ToolStripMenuItem addListFromXMLToolStripMenuItem;
		private System.ComponentModel.IContainer components;

		public MainApp()
		{

			configFile=Application.StartupPath+"\\Config.dat";

			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			this.treeViewStruct.ExpandAll();

			timer.Interval = 200;
			timer.Tick += new EventHandler(timer_Tick);
		}


		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainApp));
            this.imageListTreeView = new System.Windows.Forms.ImageList(this.components);
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.imageListDrag = new System.Windows.Forms.ImageList(this.components);
            this.MainMenu = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.StructOpenMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.StructSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.populateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.contentTypesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.ContentTypesLoadMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.ContentTypesSaveMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.userToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabPage1 = new System.Windows.Forms.TabPage();
            this.btnReload = new System.Windows.Forms.Button();
            this.txtDataFile = new System.Windows.Forms.TextBox();
            this.treeViewStruct = new System.Windows.Forms.TreeView();
            this.StructContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.EditStructMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.RemoveStructMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tabPage2 = new System.Windows.Forms.TabPage();
            this.txtItemTypes = new System.Windows.Forms.TextBox();
            this.treeViewContentTypes = new System.Windows.Forms.TreeView();
            this.ContentTypesContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.editContentTypeMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.removeContentTypeMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tabPage3 = new System.Windows.Forms.TabPage();
            this.rtRenameLog = new System.Windows.Forms.RichTextBox();
            this.rdDomain = new System.Windows.Forms.RadioButton();
            this.rdUser = new System.Windows.Forms.RadioButton();
            this.btnRename = new System.Windows.Forms.Button();
            this.txtOldPattern = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtNewPattern = new System.Windows.Forms.TextBox();
            this.tabPage4 = new System.Windows.Forms.TabPage();
            this.txtLog = new System.Windows.Forms.TextBox();
            this.addListFromXMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.MainMenu.SuspendLayout();
            this.tabControl1.SuspendLayout();
            this.tabPage1.SuspendLayout();
            this.StructContextMenu.SuspendLayout();
            this.tabPage2.SuspendLayout();
            this.ContentTypesContextMenu.SuspendLayout();
            this.tabPage3.SuspendLayout();
            this.tabPage4.SuspendLayout();
            this.SuspendLayout();
            // 
            // imageListTreeView
            // 
            this.imageListTreeView.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListTreeView.ImageStream")));
            this.imageListTreeView.TransparentColor = System.Drawing.Color.Transparent;
            this.imageListTreeView.Images.SetKeyName(0, "");
            this.imageListTreeView.Images.SetKeyName(1, "");
            this.imageListTreeView.Images.SetKeyName(2, "");
            // 
            // imageListDrag
            // 
            this.imageListDrag.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListDrag.ImageStream")));
            this.imageListDrag.TransparentColor = System.Drawing.Color.Transparent;
            this.imageListDrag.Images.SetKeyName(0, "");
            this.imageListDrag.Images.SetKeyName(1, "");
            // 
            // MainMenu
            // 
            this.MainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem,
            this.contentTypesToolStripMenuItem,
            this.userToolStripMenuItem});
            this.MainMenu.Location = new System.Drawing.Point(0, 0);
            this.MainMenu.Name = "MainMenu";
            this.MainMenu.Size = new System.Drawing.Size(600, 24);
            this.MainMenu.TabIndex = 13;
            this.MainMenu.Text = "menuStrip1";
            // 
            // fileToolStripMenuItem
            // 
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.StructOpenMenuItem,
            this.StructSaveMenuItem,
            this.populateToolStripMenuItem,
            this.exitToolStripMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
            this.fileToolStripMenuItem.Text = "&File";
            // 
            // StructOpenMenuItem
            // 
            this.StructOpenMenuItem.Name = "StructOpenMenuItem";
            this.StructOpenMenuItem.Size = new System.Drawing.Size(116, 22);
            this.StructOpenMenuItem.Text = "&Open";
            this.StructOpenMenuItem.Click += new System.EventHandler(this.StructOpenMenuItem_Click);
            // 
            // StructSaveMenuItem
            // 
            this.StructSaveMenuItem.Name = "StructSaveMenuItem";
            this.StructSaveMenuItem.Size = new System.Drawing.Size(116, 22);
            this.StructSaveMenuItem.Text = "&Save";
            this.StructSaveMenuItem.Click += new System.EventHandler(this.storeToolStripMenuItem_Click_1);
            // 
            // populateToolStripMenuItem
            // 
            this.populateToolStripMenuItem.Name = "populateToolStripMenuItem";
            this.populateToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
            this.populateToolStripMenuItem.Text = "&Populate";
            this.populateToolStripMenuItem.Click += new System.EventHandler(this.populateToolStripMenuItem_Click);
            // 
            // exitToolStripMenuItem
            // 
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
            this.exitToolStripMenuItem.Text = "&Exit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            // 
            // contentTypesToolStripMenuItem
            // 
            this.contentTypesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.ContentTypesLoadMenuItem,
            this.ContentTypesSaveMenuItem});
            this.contentTypesToolStripMenuItem.Name = "contentTypesToolStripMenuItem";
            this.contentTypesToolStripMenuItem.Size = new System.Drawing.Size(90, 20);
            this.contentTypesToolStripMenuItem.Text = "&Content Types";
            // 
            // ContentTypesLoadMenuItem
            // 
            this.ContentTypesLoadMenuItem.Name = "ContentTypesLoadMenuItem";
            this.ContentTypesLoadMenuItem.Size = new System.Drawing.Size(100, 22);
            this.ContentTypesLoadMenuItem.Text = "&Open";
            this.ContentTypesLoadMenuItem.Click += new System.EventHandler(this.ContentTypesLoadMenuItem_Click);
            // 
            // ContentTypesSaveMenuItem
            // 
            this.ContentTypesSaveMenuItem.Name = "ContentTypesSaveMenuItem";
            this.ContentTypesSaveMenuItem.Size = new System.Drawing.Size(100, 22);
            this.ContentTypesSaveMenuItem.Text = "&Save";
            this.ContentTypesSaveMenuItem.Click += new System.EventHandler(this.ContentTypesSaveMenuItem_Click);
            // 
            // userToolStripMenuItem
            // 
            this.userToolStripMenuItem.Name = "userToolStripMenuItem";
            this.userToolStripMenuItem.Size = new System.Drawing.Size(41, 20);
            this.userToolStripMenuItem.Text = "&User";
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabPage1);
            this.tabControl1.Controls.Add(this.tabPage2);
            this.tabControl1.Controls.Add(this.tabPage3);
            this.tabControl1.Controls.Add(this.tabPage4);
            this.tabControl1.Location = new System.Drawing.Point(12, 37);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(556, 349);
            this.tabControl1.TabIndex = 14;
            // 
            // tabPage1
            // 
            this.tabPage1.Controls.Add(this.btnReload);
            this.tabPage1.Controls.Add(this.txtDataFile);
            this.tabPage1.Controls.Add(this.treeViewStruct);
            this.tabPage1.Location = new System.Drawing.Point(4, 22);
            this.tabPage1.Name = "tabPage1";
            this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage1.Size = new System.Drawing.Size(548, 323);
            this.tabPage1.TabIndex = 0;
            this.tabPage1.Text = "Data";
            this.tabPage1.UseVisualStyleBackColor = true;
            // 
            // btnReload
            // 
            this.btnReload.Location = new System.Drawing.Point(223, 297);
            this.btnReload.Name = "btnReload";
            this.btnReload.Size = new System.Drawing.Size(75, 23);
            this.btnReload.TabIndex = 8;
            this.btnReload.Text = "&Reload";
            this.btnReload.UseVisualStyleBackColor = true;
            this.btnReload.Click += new System.EventHandler(this.btnReload_Click);
            // 
            // txtDataFile
            // 
            this.txtDataFile.Location = new System.Drawing.Point(0, 297);
            this.txtDataFile.Name = "txtDataFile";
            this.txtDataFile.Size = new System.Drawing.Size(216, 20);
            this.txtDataFile.TabIndex = 7;
            this.txtDataFile.Text = "struct.xml";
            // 
            // treeViewStruct
            // 
            this.treeViewStruct.AllowDrop = true;
            this.treeViewStruct.ContextMenuStrip = this.StructContextMenu;
            this.treeViewStruct.ImageIndex = 0;
            this.treeViewStruct.ImageList = this.imageListTreeView;
            this.treeViewStruct.LabelEdit = true;
            this.treeViewStruct.Location = new System.Drawing.Point(6, 6);
            this.treeViewStruct.Name = "treeViewStruct";
            this.treeViewStruct.SelectedImageIndex = 0;
            this.treeViewStruct.Size = new System.Drawing.Size(521, 277);
            this.treeViewStruct.TabIndex = 6;
            this.treeViewStruct.GiveFeedback += new System.Windows.Forms.GiveFeedbackEventHandler(this.treeViewStruct_GiveFeedback);
            this.treeViewStruct.DragLeave += new System.EventHandler(this.treeViewStruct_DragLeave);
            this.treeViewStruct.AfterLabelEdit += new System.Windows.Forms.NodeLabelEditEventHandler(this.treeViewStruct_AfterLabelEdit);
            this.treeViewStruct.MouseUp += new System.Windows.Forms.MouseEventHandler(this.treeViewStruct_MouseUp);
            this.treeViewStruct.DragDrop += new System.Windows.Forms.DragEventHandler(this.treeViewStruct_DragDrop);
            this.treeViewStruct.DragEnter += new System.Windows.Forms.DragEventHandler(this.treeViewStruct_DragEnter);
            this.treeViewStruct.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.treeViewStruct_ItemDrag);
            this.treeViewStruct.DragOver += new System.Windows.Forms.DragEventHandler(this.treeViewStruct_DragOver);
            // 
            // StructContextMenu
            // 
            this.StructContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.EditStructMenuItem,
            this.importToolStripMenuItem,
            this.RemoveStructMenuItem,
            this.addListFromXMLToolStripMenuItem});
            this.StructContextMenu.Name = "contextMenuStruct";
            this.StructContextMenu.Size = new System.Drawing.Size(157, 114);
            // 
            // EditStructMenuItem
            // 
            this.EditStructMenuItem.Name = "EditStructMenuItem";
            this.EditStructMenuItem.Size = new System.Drawing.Size(156, 22);
            this.EditStructMenuItem.Text = "&Edit";
            this.EditStructMenuItem.Click += new System.EventHandler(this.EditStructMenuItem_Click);
            // 
            // importToolStripMenuItem
            // 
            this.importToolStripMenuItem.Name = "importToolStripMenuItem";
            this.importToolStripMenuItem.Size = new System.Drawing.Size(156, 22);
            this.importToolStripMenuItem.Text = "&Import";
            this.importToolStripMenuItem.Click += new System.EventHandler(this.importToolStripMenuItem_Click);
            // 
            // RemoveStructMenuItem
            // 
            this.RemoveStructMenuItem.Name = "RemoveStructMenuItem";
            this.RemoveStructMenuItem.Size = new System.Drawing.Size(156, 22);
            this.RemoveStructMenuItem.Text = "&Remove";
            this.RemoveStructMenuItem.Click += new System.EventHandler(this.RemoveStructMenuItem_Click);
            // 
            // tabPage2
            // 
            this.tabPage2.Controls.Add(this.txtItemTypes);
            this.tabPage2.Controls.Add(this.treeViewContentTypes);
            this.tabPage2.Location = new System.Drawing.Point(4, 22);
            this.tabPage2.Name = "tabPage2";
            this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage2.Size = new System.Drawing.Size(548, 323);
            this.tabPage2.TabIndex = 1;
            this.tabPage2.Text = "Content Types";
            this.tabPage2.UseVisualStyleBackColor = true;
            // 
            // txtItemTypes
            // 
            this.txtItemTypes.Location = new System.Drawing.Point(11, 297);
            this.txtItemTypes.Name = "txtItemTypes";
            this.txtItemTypes.Size = new System.Drawing.Size(216, 20);
            this.txtItemTypes.TabIndex = 9;
            this.txtItemTypes.Text = "ItemTypes.xml";
            // 
            // treeViewContentTypes
            // 
            this.treeViewContentTypes.AllowDrop = true;
            this.treeViewContentTypes.ContextMenuStrip = this.ContentTypesContextMenu;
            this.treeViewContentTypes.ImageIndex = 0;
            this.treeViewContentTypes.ImageList = this.imageListTreeView;
            this.treeViewContentTypes.LabelEdit = true;
            this.treeViewContentTypes.Location = new System.Drawing.Point(17, 6);
            this.treeViewContentTypes.Name = "treeViewContentTypes";
            this.treeViewContentTypes.SelectedImageIndex = 0;
            this.treeViewContentTypes.Size = new System.Drawing.Size(521, 277);
            this.treeViewContentTypes.TabIndex = 8;
            // 
            // ContentTypesContextMenu
            // 
            this.ContentTypesContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.editContentTypeMenuItem,
            this.removeContentTypeMenuItem});
            this.ContentTypesContextMenu.Name = "ContentTypesContextMenu";
            this.ContentTypesContextMenu.Size = new System.Drawing.Size(114, 48);
            // 
            // editContentTypeMenuItem
            // 
            this.editContentTypeMenuItem.Name = "editContentTypeMenuItem";
            this.editContentTypeMenuItem.Size = new System.Drawing.Size(113, 22);
            this.editContentTypeMenuItem.Text = "&Edit";
            this.editContentTypeMenuItem.Click += new System.EventHandler(this.editContentTypeMenuItem_Click);
            // 
            // removeContentTypeMenuItem
            // 
            this.removeContentTypeMenuItem.Name = "removeContentTypeMenuItem";
            this.removeContentTypeMenuItem.Size = new System.Drawing.Size(113, 22);
            this.removeContentTypeMenuItem.Text = "&Remove";
            this.removeContentTypeMenuItem.Click += new System.EventHandler(this.removeContentTypeMenuItem_Click);
            // 
            // tabPage3
            // 
            this.tabPage3.Controls.Add(this.rtRenameLog);
            this.tabPage3.Controls.Add(this.rdDomain);
            this.tabPage3.Controls.Add(this.rdUser);
            this.tabPage3.Controls.Add(this.btnRename);
            this.tabPage3.Controls.Add(this.txtOldPattern);
            this.tabPage3.Controls.Add(this.label1);
            this.tabPage3.Controls.Add(this.label2);
            this.tabPage3.Controls.Add(this.txtNewPattern);
            this.tabPage3.Location = new System.Drawing.Point(4, 22);
            this.tabPage3.Name = "tabPage3";
            this.tabPage3.Size = new System.Drawing.Size(548, 323);
            this.tabPage3.TabIndex = 2;
            this.tabPage3.Text = "Users";
            this.tabPage3.UseVisualStyleBackColor = true;
            // 
            // rtRenameLog
            // 
            this.rtRenameLog.Location = new System.Drawing.Point(6, 170);
            this.rtRenameLog.Name = "rtRenameLog";
            this.rtRenameLog.Size = new System.Drawing.Size(441, 96);
            this.rtRenameLog.TabIndex = 20;
            this.rtRenameLog.Text = "";
            // 
            // rdDomain
            // 
            this.rdDomain.AutoSize = true;
            this.rdDomain.Location = new System.Drawing.Point(11, 39);
            this.rdDomain.Name = "rdDomain";
            this.rdDomain.Size = new System.Drawing.Size(61, 17);
            this.rdDomain.TabIndex = 19;
            this.rdDomain.Text = "Domain";
            this.rdDomain.UseVisualStyleBackColor = true;
            // 
            // rdUser
            // 
            this.rdUser.AutoSize = true;
            this.rdUser.Checked = true;
            this.rdUser.Location = new System.Drawing.Point(11, 16);
            this.rdUser.Name = "rdUser";
            this.rdUser.Size = new System.Drawing.Size(47, 17);
            this.rdUser.TabIndex = 19;
            this.rdUser.TabStop = true;
            this.rdUser.Text = "User";
            this.rdUser.UseVisualStyleBackColor = true;
            // 
            // btnRename
            // 
            this.btnRename.Location = new System.Drawing.Point(6, 297);
            this.btnRename.Name = "btnRename";
            this.btnRename.Size = new System.Drawing.Size(75, 23);
            this.btnRename.TabIndex = 18;
            this.btnRename.Text = "&Rename";
            this.btnRename.Click += new System.EventHandler(this.btnRename_Click);
            // 
            // txtOldPattern
            // 
            this.txtOldPattern.Location = new System.Drawing.Point(170, 79);
            this.txtOldPattern.Name = "txtOldPattern";
            this.txtOldPattern.Size = new System.Drawing.Size(277, 20);
            this.txtOldPattern.TabIndex = 14;
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(3, 128);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(161, 20);
            this.label1.TabIndex = 13;
            this.label1.Text = "New name (case sensitive)";
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(3, 83);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(161, 16);
            this.label2.TabIndex = 13;
            this.label2.Text = "Old name (case sensitive)";
            // 
            // txtNewPattern
            // 
            this.txtNewPattern.Location = new System.Drawing.Point(170, 128);
            this.txtNewPattern.Name = "txtNewPattern";
            this.txtNewPattern.Size = new System.Drawing.Size(277, 20);
            this.txtNewPattern.TabIndex = 15;
            // 
            // tabPage4
            // 
            this.tabPage4.Controls.Add(this.txtLog);
            this.tabPage4.Location = new System.Drawing.Point(4, 22);
            this.tabPage4.Name = "tabPage4";
            this.tabPage4.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage4.Size = new System.Drawing.Size(548, 323);
            this.tabPage4.TabIndex = 3;
            this.tabPage4.Text = "Log";
            this.tabPage4.UseVisualStyleBackColor = true;
            // 
            // txtLog
            // 
            this.txtLog.Location = new System.Drawing.Point(6, 6);
            this.txtLog.Multiline = true;
            this.txtLog.Name = "txtLog";
            this.txtLog.Size = new System.Drawing.Size(536, 311);
            this.txtLog.TabIndex = 1;
            // 
            // addListFromXMLToolStripMenuItem
            // 
            this.addListFromXMLToolStripMenuItem.Name = "addListFromXMLToolStripMenuItem";
            this.addListFromXMLToolStripMenuItem.Size = new System.Drawing.Size(156, 22);
            this.addListFromXMLToolStripMenuItem.Text = "&Add list from XML";
            this.addListFromXMLToolStripMenuItem.Click += new System.EventHandler(this.addListFromXMLToolStripMenuItem_Click);
            // 
            // MainApp
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(600, 393);
            this.Controls.Add(this.tabControl1);
            this.Controls.Add(this.MainMenu);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MainMenuStrip = this.MainMenu;
            this.Name = "MainApp";
            this.Text = "Extracted Data Reorganizer";
            this.Load += new System.EventHandler(this.MainApp_Load);
            this.MainMenu.ResumeLayout(false);
            this.MainMenu.PerformLayout();
            this.tabControl1.ResumeLayout(false);
            this.tabPage1.ResumeLayout(false);
            this.tabPage1.PerformLayout();
            this.StructContextMenu.ResumeLayout(false);
            this.tabPage2.ResumeLayout(false);
            this.tabPage2.PerformLayout();
            this.ContentTypesContextMenu.ResumeLayout(false);
            this.tabPage3.ResumeLayout(false);
            this.tabPage3.PerformLayout();
            this.tabPage4.ResumeLayout(false);
            this.tabPage4.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new MainApp());
		}


		private void MainApp_Load(object sender, System.EventArgs e)
		{
			
			try 
			{
				// Create an instance of StreamReader to read from a file.
				// The using statement also closes the StreamReader.
				using(StreamReader sr = new StreamReader(configFile))
				{
					String line=sr.ReadLine();
					txtDataFile.Text=line;
			
				}
			}
			catch (ArgumentException argEx) 
			{
				Logger.Log(ErrorLevel.NoLog,"Error :"+argEx.Message);
			}
			catch (IOException ex) 
			{
				// Let the user know what went wrong.
				Console.WriteLine("The file could not be read:");
				Console.WriteLine(ex.Message);
			}
			
			
		}
		private void RenameUsersInItemsFile(SharePoint.ImportExport.Core.Site Site, string oldValue,string newValue)
		{
            this.rtRenameLog.AppendText("Processing datafiles\r\n");

			foreach(List List in Site.Lists)
			{
				//
				string fileName=txtDataFile.Text.Substring(0,txtDataFile.Text.LastIndexOf("\\"))+List.RelativeitemXML;
				string data=String.Empty;
                this.rtRenameLog.AppendText("Processing file:" + fileName + "\r\n");
    
				using(StreamReader sr=new StreamReader(fileName))
				{
					data=sr.ReadToEnd();
					data=data.Replace(oldValue,newValue);
					sr.Close();
				}
				if(data.Length>0)
				{
					using(StreamWriter sw=new StreamWriter(fileName,false))
					{
						sw.Write(data);
						sw.Flush();
						sw.Close();
					}

				}
				System.Diagnostics.Debug.WriteLine(fileName);
			}
		}


		private void treeViewStruct_AfterLabelEdit(object sender, System.Windows.Forms.NodeLabelEditEventArgs e)
		{
			TreeNode node = e.Node;
			if(null!=node)
			{
				if(node.Tag!=null)
				{
					SharePoint.ImportExport.Core.Site site=null;
					SharePoint.ImportExport.Core.Root root=null;
					SharePoint.ImportExport.Core.List list=null;
					switch(node.Tag.GetType().ToString())
					{
						case "SharePoint.ImportExport.Core.Root":
						{
							root=(SharePoint.ImportExport.Core.Root)node.Tag;
							break;
						}
						case "SharePoint.ImportExport.Core.Site":
						{
							site=(SharePoint.ImportExport.Core.Site)node.Tag;
							break;
						}
						case "SharePoint.ImportExport.Core.List":
						{
							list=(SharePoint.ImportExport.Core.List)node.Tag;
							break;
						}
					}
				}
			}
		}



        
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool bPropmt = true;
            if (DataChanged)
            {
                DialogResult dataresult = MessageBox.Show("Data changed, exit without saving?", "Close Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                if (dataresult == DialogResult.No)
                    return;
                bPropmt = false;
            }
            if (TemplateDataChanged)
            {
                DialogResult dataresult = MessageBox.Show("Template Data changed, exit without saving?", "Close Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                if (dataresult == DialogResult.No)
                    return;
                bPropmt = false;
            }
            DialogResult result = DialogResult.Yes;
            if(bPropmt)
                result = MessageBox.Show("Are you sure you'd like to exit?", "Close Application", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            if (result == DialogResult.Yes)
            {
                try
                {


                    // Create an instance of StreamWriter to write to a file.
                    using (StreamWriter sw = new StreamWriter(configFile, false))
                    {
                        sw.WriteLine(txtDataFile.Text);
                        sw.Flush();
                        sw.Close();
                    }
                }
                catch (IOException Ex)
                {
                    Logger.Log(ErrorLevel.Information, "Could not write to config.dat. Error:" + Ex.Message);
                }
                this.Close();
            }
		

        }

    
        private void ContentTypesLoadMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.DefaultExt = "xml";
            
            if (File.Exists(txtItemTypes.Text))
                openFileDialog1.FileName = txtItemTypes.Text;
            if (DialogResult.OK == openFileDialog1.ShowDialog())
            {
                txtItemTypes.Text = openFileDialog1.FileName;
                LoadContentTypes(txtItemTypes.Text);
            }

        }
 



        #region ContentTypes
        private bool LoadContentTypes(string fileName)
        {
          bool retValue=false;
          if (!File.Exists(fileName))
            {
                txtLog.Text += "File " + fileName + " does not exist";
                return retValue;
            }
            treeViewContentTypes.Nodes.Clear();
            treeViewContentTypes.LabelEdit = true;
            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream(fileName, FileMode.Open);
            XmlReader reader = new XmlTextReader(fs);
            try
            {
                // Create an instance of the XmlSerializer specifying type and namespace.
                XmlSerializer serializer = new XmlSerializer(typeof(ListOfContentTypes));
                // Use the Deserialize method to restore the object's state.
                templates = (ListOfContentTypes)serializer.Deserialize(reader);

                txtLog.Text += "\r\nData loaded OK";
                foreach (ContentType template in templates.ContentTypesCollection)
                {
                    TreeNode node = new TreeNode(template.Name, 0, 0);
                    node.Tag = template;
                    treeViewContentTypes.Nodes.Add(node);
                    EnumTemplates(template, node);
                }
            }
            catch (Exception Ex)
            {
                txtLog.Text +="\r\nErrors when deserializing the data. Error: " + System.Environment.NewLine + Ex.Message;
            }
            finally
            {
                reader.Close();
                fs.Close();
            }
        

            return retValue;
        }
        private bool SaveContentTypes()
        {
            bool retValue = false;
            ListOfContentTypes ItemTypesFixed = new ListOfContentTypes();
            

            string newname = helperFunction.RenameFile(txtItemTypes.Text);
            if (File.Exists(newname))
            {
                string message = "File " + newname + " already exists OK to overwrite Y/N";
                if (DialogResult.Yes == MessageBox.Show(message, "File exists", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question))
                {
                    File.Copy(txtItemTypes.Text, newname, true);
                }
                else
                    return false;

            }
            else
                File.Copy(txtItemTypes.Text, newname, false);

            foreach (TreeNode rootnode in treeViewContentTypes .Nodes)
            {
                if (rootnode.Tag != null)
                {

                    string type = rootnode.Tag.GetType().ToString();
                    switch (type)
                    {

                        case "SharePoint.ImportExport.Core.ContentType":
                            ItemTypesFixed.ContentTypesCollection.Add((ContentType)rootnode.Tag);
                            break;
                    }
                }
            }
            //Validate the schema prior to saving
            if (!ItemTypesFixed.Validate())
                txtLog.Text +="\r\n(Validation failed, last error: " + ItemTypesFixed.LastError;
            else
            {

                try
                {
                    ItemTypesFixed.Serialize(txtItemTypes.Text);
                    txtLog.Text +="\r\nData saved to file " + txtItemTypes.Text;
                    retValue = true;

                    templates = ItemTypesFixed;
                }
                catch (SPExportException ex)
                {
                    txtLog.Text +="\r\n(Exception occurred: " + ex.Message;
                }
            }
            return retValue;

        }
        private void ContentTypesSaveMenuItem_Click(object sender, EventArgs e)
        {
            SaveContentTypes();
        }

   

        
        private void editContentTypeMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewContentTypes.SelectedNode;
            if (null != node)
            {
                if (node.Tag != null)
                {

                    SharePoint.ImportExport.Core.ContentType template = null;
                    switch (node.Tag.GetType().ToString())
                    {
                        case "SharePoint.ImportExport.Core.ContentType":
                            {
                                template = (SharePoint.ImportExport.Core.ContentType)node.Tag;
                                frmEditListTemplate frm = new frmEditListTemplate(template);
                                if (frm.ShowDialog() == DialogResult.OK)
                                {
                                    TemplateDataChanged = true;
                                    if(frm.TemplateChanged)
                                        node.Tag = frm.template;
                                    if (node.Text != template.Name)
                                    {

                                        if (DialogResult.Yes == MessageBox.Show("You should apply these changes to all lists and sites that use the lists, do you want to do it?", "Schema changes", MessageBoxButtons.YesNoCancel))
                                        {
                                            if (SaveStruct(false))
                                            {
                                                foreach (SharePoint.ImportExport.Core.Site c in importStructure.RootContainers[0].Sites)
                                                {
                                                    foreach (List dc in c.Lists)
                                                    {
                                                        if (dc.Template == node.Text)
                                                        {
                                                            FileInfo fi = new FileInfo(txtDataFile.Text);
                                                            string copyname=helperFunction.RenameFile(fi.DirectoryName + dc.RelativeitemXML);
                                                            File.Copy(fi.DirectoryName + dc.RelativeitemXML, copyname);
                                                            string s = File.ReadAllText(fi.DirectoryName + dc.RelativeitemXML);
                                                            s = s.Replace("=\"" + node.Text, "=\"" + template.Name);
                                                            File.WriteAllText(fi.DirectoryName + dc.RelativeitemXML, s);
                                                            dc.Template = template.Name;
                                                        }
                                                    }
                                                    SaveStruct(false);
                                                }
                                            }

                                        }
                                        node.Text = template.Name;

                                    }

                                }

                                break;
                            }
                    }
                }
            }

        }
        private void removeContentTypeMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewContentTypes.SelectedNode;
            if (null != node)
            {
                if (node.Tag != null)
                {

                    SharePoint.ImportExport.Core.ItemType template = null;
                    if("SharePoint.ImportExport.Core.ItemType"==(node.Tag.GetType().ToString()))
                    {
                        template = (SharePoint.ImportExport.Core.ItemType)node.Tag;
                        treeViewContentTypes.Nodes.Remove(node);
                        TemplateDataChanged = true;

                    }
                                
                }
            }

        }

        static void EnumTemplates(ContentType template, TreeNode node)
        {

            TreeNode fieldsRootNode = new TreeNode("Fields", 2, 3);
            node.Nodes.Add(fieldsRootNode);
            foreach (SharePoint.ImportExport.Core.Field field in template.Fields)
            {
                string s = field.DisplayName + "(" + field.Name + ")," + field.ExtendedType.ToString();
                TreeNode fNode = new TreeNode(s, 2, 3);
                fNode.Tag = field;
                fieldsRootNode.Nodes.Add(fNode);

            }
        }
#endregion
        #region Struct
        private bool LoadData(string fileName)
        {
            bool retValue=false;
            if (!File.Exists(fileName))
            {
                txtLog.Text += "\r\nFile " + fileName + " does not exist";
                return retValue;
            }
            treeViewStruct.Nodes.Clear();
            treeViewStruct.LabelEdit = true;
            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream(fileName, FileMode.Open);
            XmlReader reader = new XmlTextReader(fs);
            try
            {
                // Create an instance of the XmlSerializer specifying type and namespace.
                XmlSerializer serializer = new XmlSerializer(typeof(Import));
                // Use the Deserialize method to restore the object's state.
                importStructure = (Import)serializer.Deserialize(reader);

                txtLog.Text += "\r\nData loaded OK";
                foreach (Root root in importStructure.RootContainers)
                {

                    TreeNode node = new TreeNode(root.Name, 0, 0);
                    node.Tag = root;
                    treeViewStruct.Nodes.Add(node);
                    EnumSites(root.Sites, node);


                }
            }
            catch (Exception Ex)
            {
                txtLog.Text += "\r\nErrors when deserializing the data. Error: " + System.Environment.NewLine + Ex.Message;
            }
            finally
            {
                reader.Close();
                fs.Close();
            }

            return retValue;
        }
        private void StructOpenMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.DefaultExt = "xml";
            if (File.Exists(txtDataFile.Text))
                openFileDialog1.FileName = txtDataFile.Text;
            if (DialogResult.OK == openFileDialog1.ShowDialog())
            {
                txtDataFile.Text = openFileDialog1.FileName;
                LoadData(txtDataFile.Text);
                FileInfo fi=new FileInfo(txtDataFile.Text);
                if(File.Exists(fi.DirectoryName+"\\ItemTypes.xml"))
                {
                    LoadContentTypes(fi.DirectoryName+"\\ItemTypes.xml");
                }
            }
        }
        private bool SaveStruct(bool prompt)
        {
            bool retValue = false;
            Import importFixed = new Import();
            string newname = txtDataFile.Text;
            if (File.Exists(txtDataFile.Text))
                newname = helperFunction.RenameFile(txtDataFile.Text);
            if (File.Exists(newname) && prompt)
            {
                string message = "File " + newname + " already exists OK to overwrite Y/N";
                if (DialogResult.Yes == MessageBox.Show(message, "File exists", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question))
                {
                    File.Copy(txtDataFile.Text, newname, true);
                }
                else
                    return false;

            }
            else
            {
                File.Copy(txtDataFile.Text, newname, false);
                txtLog.Text +="\r\nBackup file created to "+newname;

              }

            importFixed.Settings.Locale = importStructure.Settings.Locale;
            foreach (TreeNode rootnode in treeViewStruct.Nodes)
            {
                if (rootnode.Tag != null)
                {

                    string type = rootnode.Tag.GetType().ToString();
                    switch (type)
                    {
                        case "SharePoint.ImportExport.Core.Root":
                            importFixed.RootContainers.Add((Root)rootnode.Tag);
                            break;
                    }
                }
            }
            //Validate the schema prior to saving
            if (!importFixed.Validate())
                txtLog.Text +="\r\nValidation failed, last error: " + importFixed.LastError;
            else
            {

                try
                {
                    importFixed.Serialize(txtDataFile.Text);
                    txtLog.Text += "\r\nData saved to file " + txtDataFile.Text;
                    retValue = true;
                    DataChanged = false;

                    importStructure = importFixed;
                }
                catch (SPExportException ex)
                {
                    txtLog.Text +="\r\nException occurred: " + ex.Message;
                }
            }
            return retValue;

        }

        private void StructSaveMenuItem_Click(object sender, EventArgs e)
        {
            SaveStruct(true);
        }

        private void RemoveStructMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewStruct.SelectedNode;
            if (null != node)
            {
                if (node.Tag != null)
                {
                    if (node.Tag.GetType().ToString() == "SharePoint.ImportExport.Core.User")
                    {
                        SharePoint.ImportExport.Core.Site parentSite = (SharePoint.ImportExport.Core.Site)node.Parent.Parent.Tag;
                        if (parentSite.UserInfo.Users.Remove(node.Text))
                        {
                            DataChanged = true;
                            node.Parent.Nodes.Remove(node);
                        }

                    }
                    else
                    {

                        SharePoint.ImportExport.Core.Site parentSite = null;
                        SharePoint.ImportExport.Core.Root parentRootContainer = null;
                        SharePoint.ImportExport.Core.List parentList = null;
                        switch (node.Parent.Tag.GetType().ToString())
                        {
                            case "SharePoint.ImportExport.Core.Root":
                                {
                                    parentRootContainer = (SharePoint.ImportExport.Core.Root)node.Parent.Tag;
                                    if (parentRootContainer.Sites.Remove(node.Text))
                                    {
                                        DataChanged = true;
                                        node.Parent.Nodes.Remove(node);
                                    }

                                    break;
                                }
                            case "SharePoint.ImportExport.Core.Site":
                                {
                                    parentSite = (SharePoint.ImportExport.Core.Site)node.Parent.Tag;
                                    switch (node.Tag.GetType().ToString())
                                    {

                                        case "SharePoint.ImportExport.Core.Site":
                                            {
                                                if (parentSite.SubSites.Remove(node.Text))
                                                {
                                                    DataChanged = true;
                                                    node.Parent.Nodes.Remove(node);
                                                }

                                                break;
                                            }
                                        case "SharePoint.ImportExport.Core.List":
                                            {
                                                if (parentSite.Lists.Remove(node.Text))
                                                {
                                                    DataChanged = true;
                                                    node.Parent.Nodes.Remove(node);
                                                }

                                                break;
                                            }
                                    }
                                    break;
                                }
                            case "SharePoint.ImportExport.Core.List":
                                {
                                    parentList = (List)node.Parent.Tag;
                                    switch (node.Tag.GetType().ToString())
                                    {
                                        case "SharePoint.ImportExport.Core.List":
                                            {
                                                if (parentList.Folders.Remove(node.Text))
                                                {
                                                    DataChanged = true;
                                                    node.Parent.Nodes.Remove(node);
                                                }
                                                break;
                                            }
                                    }
                                    break;
                                }
                        }
                    }
                }
            }

        }

        private void EditStructMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewStruct.SelectedNode;
            if (null != node)
            {
                if (node.Tag != null)
                {

                    SharePoint.ImportExport.Core.Site parentSite = null;
                    SharePoint.ImportExport.Core.Root parentRootContainer = null;
                    SharePoint.ImportExport.Core.List parentList = null;
                    switch (node.Tag.GetType().ToString())
                    {
                        case "SharePoint.ImportExport.Core.Root":
                            {
                                parentRootContainer = (SharePoint.ImportExport.Core.Root)node.Tag;

                                break;
                            }
                        case "SharePoint.ImportExport.Core.Site":
                            {
                                parentSite = (SharePoint.ImportExport.Core.Site)node.Tag;
                                frmEditSite frm = new frmEditSite(parentSite);
                                if (DialogResult.OK == frm.ShowDialog())
                                {
                                    if (node.Text != parentSite.Name)
                                        node.Text = parentSite.Name;
                                    DataChanged = true;

                                }
                                break;
                            }

                        case "SharePoint.ImportExport.Core.List":
                            {
                                parentList = (SharePoint.ImportExport.Core.List)node.Tag;
                                FileInfo fi = new FileInfo(txtDataFile.Text);
                                frmEditList frm = new frmEditList(parentList,fi.DirectoryName);
                                if (DialogResult.OK == frm.ShowDialog())
                                {
                                    DataChanged = true;
                                    if (node.Text != parentList.Name)
                                        node.Text = parentList.Name;
                                }
                                break;
                            }
                    }
                }
            }


        }

        private void storeToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            SaveStruct(true);
        }
        static void EnumLists(ListsCollection Lists, TreeNode node)
        {

            foreach (SharePoint.ImportExport.Core.List parentList in Lists)
            {
                TreeNode dataNode = new TreeNode(parentList.Name, 1, 1);
                dataNode.Tag = parentList;
                node.Nodes.Add(dataNode);
                EnumLists(parentList.Folders, dataNode);

            }
        }
        static void EnumSites(SitesCollection Sites, TreeNode node)
        {

            foreach (SharePoint.ImportExport.Core.Site parentSite in Sites)
            {
                TreeNode siteCollectionRootNode = new TreeNode(parentSite.Name, 0, 0);
                siteCollectionRootNode.Tag = parentSite;
                node.Nodes.Add(siteCollectionRootNode);
                TreeNode userRootNode = new TreeNode("Users", 2, 3);
                siteCollectionRootNode.Nodes.Add(userRootNode);
                foreach (User user in parentSite.UserInfo.Users)
                {
                    TreeNode userNode = new TreeNode(user.Name, 2, 3);
                    userNode.Tag = user;
                    userRootNode.Nodes.Add(userNode);
                }
                EnumSites(parentSite.SubSites, siteCollectionRootNode);
                EnumLists(parentSite.Lists, siteCollectionRootNode);

            }
        }

        private void treeViewStruct_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
        {
            // Get drag node and select it
            this.dragNode = (TreeNode)e.Item;
            this.treeViewStruct.SelectedNode = this.dragNode;

            // Reset image list used for drag image
            this.imageListDrag.Images.Clear();
            this.imageListDrag.ImageSize =
                new Size(this.dragNode.Bounds.Size.Width
                + this.treeViewStruct.Indent, this.dragNode.Bounds.Height);

            // Create new bitmap
            // This bitmap will contain the tree node image to be dragged
            Bitmap bmp = new Bitmap(this.dragNode.Bounds.Width
                + this.treeViewStruct.Indent, this.dragNode.Bounds.Height);

            // Get graphics from bitmap
            Graphics gfx = Graphics.FromImage(bmp);

            // Draw node icon into the bitmap
            gfx.DrawImage(this.imageListTreeView.Images[0], 0, 0);

            // Draw node label into bitmap
            gfx.DrawString(this.dragNode.Text,
                this.treeViewStruct.Font,
                new SolidBrush(this.treeViewStruct.ForeColor),
                (float)this.treeViewStruct.Indent, 1.0f);

            // Add bitmap to imagelist
            this.imageListDrag.Images.Add(bmp);

            // Get mouse position in client coordinates
            Point p = this.treeViewStruct.PointToClient(Control.MousePosition);

            // Compute delta between mouse position and node bounds
            int dx = p.X + this.treeViewStruct.Indent - this.dragNode.Bounds.Left;
            int dy = p.Y - this.dragNode.Bounds.Top;

            // Begin dragging image
            if (DragHelper.ImageList_BeginDrag(this.imageListDrag.Handle, 0, dx, dy))
            {
                // Begin dragging
                this.treeViewStruct.DoDragDrop(bmp, DragDropEffects.Move);
                // End dragging image
                DragHelper.ImageList_EndDrag();
            }
        }

        private void treeViewStruct_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            // Compute drag position and move image
            Point formP = this.PointToClient(new Point(e.X, e.Y));
            DragHelper.ImageList_DragMove(formP.X - this.treeViewStruct.Left, formP.Y - this.treeViewStruct.Top);

            // Get actual drop node
            TreeNode dropNode = this.treeViewStruct.GetNodeAt(this.treeViewStruct.PointToClient(new Point(e.X, e.Y)));
            if (dropNode == null)
            {
                e.Effect = DragDropEffects.None;
                return;
            }

            e.Effect = DragDropEffects.Move;

            // if mouse is on a new node select it
            if (this.tempDropNode != dropNode)
            {
                DragHelper.ImageList_DragShowNolock(false);
                this.treeViewStruct.SelectedNode = dropNode;
                DragHelper.ImageList_DragShowNolock(true);
                tempDropNode = dropNode;
            }

            // Avoid that drop node is child of drag node 
            TreeNode tmpNode = dropNode;
            while (tmpNode.Parent != null)
            {
                if (tmpNode.Parent == this.dragNode) e.Effect = DragDropEffects.None;
                tmpNode = tmpNode.Parent;
            }

        }

        private void treeViewStruct_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {

            // Unlock updates
            DragHelper.ImageList_DragLeave(this.treeViewStruct.Handle);

            if (this.dragNode.Tag == null)
            {
                MessageBox.Show("You cannot move the Users Site");
                return;
            }

            // Get drop node
            TreeNode dropNode = this.treeViewStruct.GetNodeAt(this.treeViewStruct.PointToClient(new Point(e.X, e.Y)));
            SharePoint.ImportExport.Core.Site dropTargetSite = null;
            SharePoint.ImportExport.Core.Root dropTargetRootContainer = null;
            SharePoint.ImportExport.Core.List dropTargetList = null;
            SharePoint.ImportExport.Core.Site draggedSite = null;
            SharePoint.ImportExport.Core.List draggedList = null;
            if (dropNode.Tag != null)
            {
                switch (dropNode.Tag.GetType().ToString())
                {
                    case "SharePoint.ImportExport.Core.Root":
                        {
                            dropTargetRootContainer = (SharePoint.ImportExport.Core.Root)dropNode.Tag;

                            break;
                        }
                    case "SharePoint.ImportExport.Core.Site":
                        {
                            dropTargetSite = (SharePoint.ImportExport.Core.Site)dropNode.Tag;

                            break;
                        }
                    case "SharePoint.ImportExport.Core.List":
                        {
                            dropTargetList = (List)dropNode.Tag;
                            break;
                        }
                }
            }

            // If drop node isn't equal to drag node, add drag node as child of drop node
            if (this.dragNode != dropNode)
            {
                // Remove drag node from parent
                if (this.dragNode.Parent == null)
                {
                    this.treeViewStruct.Nodes.Remove(this.dragNode);
                }
                else
                {
                    if (this.dragNode.Tag != null)
                    {
                        switch (this.dragNode.Tag.GetType().ToString())
                        {
                            case "SharePoint.ImportExport.Core.Site":
                                {
                                    draggedSite = (SharePoint.ImportExport.Core.Site)this.dragNode.Tag;

                                    break;
                                }
                            case "SharePoint.ImportExport.Core.List":
                                {
                                    draggedList = (List)this.dragNode.Tag;
                                    break;
                                }
                        }
                    }



                }

                // Add drag node to drop node
                bool added = false;
                if (dropTargetRootContainer != null)
                {
                    if (draggedSite != null)
                    {
                        if (draggedSite.Owner == null || draggedSite.Owner.Length < 1)
                            draggedSite.Owner = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                        bool nameconflict = false;
                        foreach (SharePoint.ImportExport.Core.Site cont in dropTargetRootContainer.Sites)
                        {
                            if (cont.Name == draggedSite.Name)
                            {
                                nameconflict = true;
                                break;
                            }
                        }
                        if (!nameconflict)
                        {
                            dropTargetRootContainer.Sites.Add(draggedSite);
                            DataChanged = true;
                            added = true;
                        }
                        else
                        {
                            txtLog.Text += "\r\nThe web " + dropTargetSite.Name + " already exists";
                        }
                    }
                }
                if (dropTargetSite != null)
                {
                    if (draggedSite != null)
                    {

                        bool nameconflict = false;
                        foreach (SharePoint.ImportExport.Core.Site cont in dropTargetSite.SubSites)
                        {
                            if (cont.Name == draggedSite.Name)
                            {
                                nameconflict = true;
                                break;
                            }
                        }
                        if (!nameconflict)
                        {
                            dropTargetSite.SubSites.Add(draggedSite);
                            DataChanged = true;
                            added = true;
                        }
                        else
                        {
                            txtLog.Text += "\r\nThe web " + dropTargetSite.Name + " already has a subweb called " + draggedSite.Name;
                        }
                    }
                    if (draggedList != null)
                    {
                        if (draggedList.DataType == SharePoint.ImportExport.Core.ListType.Folder)
                        {
                            TreeNode findParent = dragNode.Parent;
                            while (null != findParent && findParent.Tag.GetType().ToString() == "SharePoint.ImportExport.Core.ListType.Folder")
                            {
                                findParent = findParent.Parent;
                            }
                            List List = (List)findParent.Tag;
                            draggedList.DataType = ListType.Library;
                            draggedList.Template = List.Template;
                            draggedList.DocumentTemplateUrl = List.DocumentTemplateUrl.Replace(List.Name, draggedList.Name);
                            draggedList.WebPart = List.WebPart;
                        }
                        bool nameconflict = false;
                        foreach (List cont in dropTargetSite.Lists)
                        {
                            if (cont.Name == draggedList.Name)
                            {

                                if (DialogResult.Yes == MessageBox.Show("List \"" + cont.Name + "\" already exists in the site. \r\nDo you want to merge the content", "List already exists", MessageBoxButtons.YesNo))
                                    nameconflict = false;
                                else
                                    nameconflict = true;
                                break;
                            }
                        }
                        if (!nameconflict)
                        {
                            dropTargetSite.Lists.Add(draggedList);
                            added = true;
                            DataChanged = true;
                        }
                        else
                        {
                            txtLog.Text += "\r\nThe web " + dropTargetSite.Name + " already has a list called " + draggedList.Name;
                        }

                    }
                }
                if (dropTargetList != null)
                {
                    if (draggedList != null)
                        dropTargetList.Folders.Add(draggedList);
                }
                if (added)
                {
                    if (this.dragNode.Parent.Tag != null)
                    {
                        switch (this.dragNode.Parent.Tag.GetType().ToString())
                        {
                            case "SharePoint.ImportExport.Core.Root":
                                {
                                    Root rc = (Root)this.dragNode.Parent.Tag;
                                    rc.Sites.Remove(draggedSite.Name);
                                    break;
                                }
                            case "SharePoint.ImportExport.Core.Site":
                                {
                                    SharePoint.ImportExport.Core.Site SiteNode = (SharePoint.ImportExport.Core.Site)this.dragNode.Parent.Tag;
                                    if (draggedSite != null)
                                    {
                                        SiteNode.SubSites.Remove(draggedSite.Name);
                                    }

                                    if (draggedList != null)
                                    {
                                        SiteNode.Lists.Remove(draggedList.Name);
                                    }

                                    break;
                                }
                            case "SharePoint.ImportExport.Core.List":
                                {
                                    List List = (List)this.dragNode.Parent.Tag;
                                    if (draggedList != null)
                                    {
                                        List.Folders.Remove(draggedList.Name);
                                    }
                                    break;
                                }

                        }
                    }
                    this.dragNode.Parent.Nodes.Remove(this.dragNode);

                    dropNode.Nodes.Add(this.dragNode);
                }

                // Set drag node to null
                this.dragNode = null;

                // Disable scroll timer
                this.timer.Enabled = false;
            }

        }

        private void treeViewStruct_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
        {
            DragHelper.ImageList_DragEnter(this.treeViewStruct.Handle, e.X - this.treeViewStruct.Left,
                e.Y - this.treeViewStruct.Top);

            // Enable timer for scrolling dragged item
            this.timer.Enabled = true;

        }

        private void treeViewStruct_DragLeave(object sender, System.EventArgs e)
        {
            DragHelper.ImageList_DragLeave(this.treeViewStruct.Handle);

            // Disable timer for scrolling dragged item
            this.timer.Enabled = false;

        }

        private void treeViewStruct_GiveFeedback(object sender, System.Windows.Forms.GiveFeedbackEventArgs e)
        {
            if (e.Effect == DragDropEffects.Move)
            {
                // Show pointer cursor while dragging
                e.UseDefaultCursors = false;
                this.treeViewStruct.Cursor = Cursors.Default;
            }
            else e.UseDefaultCursors = true;

        }

        private void timer_Tick(object sender, EventArgs e)
        {
            // get node at mouse position
            Point pt = PointToClient(Control.MousePosition);
            TreeNode node = this.treeViewStruct.GetNodeAt(pt);

            if (node == null) return;

            // if mouse is near to the top, scroll up
            if (pt.Y < 30)
            {
                // set actual node to the upper one
                if (node.PrevVisibleNode != null)
                {
                    node = node.PrevVisibleNode;

                    // hide drag image
                    DragHelper.ImageList_DragShowNolock(false);
                    // scroll and refresh
                    node.EnsureVisible();
                    this.treeViewStruct.Refresh();
                    // show drag image
                    DragHelper.ImageList_DragShowNolock(true);

                }
            }
            // if mouse is near to the bottom, scroll down
            else if (pt.Y > this.treeViewStruct.Size.Height - 30)
            {
                if (node.NextVisibleNode != null)
                {
                    node = node.NextVisibleNode;

                    DragHelper.ImageList_DragShowNolock(false);
                    node.EnsureVisible();
                    this.treeViewStruct.Refresh();
                    DragHelper.ImageList_DragShowNolock(true);
                }
            }
        }



        private void treeViewStruct_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                // Get drop node
                TreeNode dropNode = this.treeViewStruct.GetNodeAt(this.treeViewStruct.PointToClient(new Point(e.X, e.Y)));
                if (dropNode == null)
                {
                    dropNode = this.treeViewStruct.GetNodeAt(new Point(e.X, e.Y));
                }
                this.treeViewStruct.SelectedNode = dropNode;
            }
        }

        #endregion

        private void btnRename_Click(object sender, EventArgs e)
        {
            if ((txtOldPattern.Text.Length == 0) || (txtNewPattern.Text.Length == 0))
            {
                MessageBox.Show("You have to specify the rename patterns");
                return;
            }
            foreach (Root root in importStructure.RootContainers)
            {
                for (int i = 0; i < root.Sites.Count; i++)
                {
                    SharePoint.ImportExport.Core.Site Site = root.Sites[i];
                    Site.Owner = Site.Owner.Replace(txtOldPattern.Text, txtNewPattern.Text);
                    for (int j = 0; j < Site.UserInfo.Users.Count; j++)
                    {
                        User user = Site.UserInfo.Users[j];
                        this.rtRenameLog.AppendText("Renaming user: " + user.Account+"\r\n");
                        user.Account = user.Account.Replace(txtOldPattern.Text, txtNewPattern.Text);
                        
                    }
                    RenameUsersInItemsFile(Site, txtOldPattern.Text, txtNewPattern.Text);
                }
            }

        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            if (File.Exists(txtDataFile.Text))
            {
                LoadData(txtDataFile.Text);
            }

        }
        void EnumAndCreateListItems(SharePoint.ImportExport.Core.List List, String DirectoryName)
        {
          foreach (List folder in List.Folders)
          {
            EnumAndCreateListItems(folder, DirectoryName);
          }
          if (File.Exists(DirectoryName + List.RelativeitemXML))
          {
            using (FileStream itemsfileStream = new FileStream(DirectoryName + List.RelativeitemXML, FileMode.Open))
            {
              FileInfo fi = new FileInfo(itemsfileStream.Name);
              using (XmlReader itemsReader = new XmlTextReader(itemsfileStream))
              {
                //// Declare an object variable of the type to be deserialized.
                SharePoint.ImportExport.Core.ListOfItems exportedList = new SharePoint.ImportExport.Core.ListOfItems();
                //// Create an instance of the XmlSerializer specifying type and namespace.
                XmlSerializer serializer2 = new XmlSerializer(typeof(SharePoint.ImportExport.Core.ListOfItems));


                exportedList = (SharePoint.ImportExport.Core.ListOfItems)serializer2.Deserialize(itemsReader);
                itemsReader.Close();
                itemsfileStream.Close();
                foreach (ItemType ct in exportedList.ItemTypes)
                {
                  foreach (Item it in ct.Items)
                  {
                    foreach (Attachment att in it.Attachments)
                    {
                      if (!File.Exists(fi.DirectoryName + "\\" + att.FileName))
                      {
                        File.WriteAllText(fi.DirectoryName + "\\" + att.FileName, "11");
                      }

                    }
                    if (it.FileName != null)
                    {
                      if (!File.Exists(fi.DirectoryName + "\\" + it.FileName))
                      {
                        File.WriteAllText(fi.DirectoryName + "\\" + it.FileName, "11");
                      }

                      foreach (Item version in it.Versions)
                      {
                        if (!File.Exists(fi.DirectoryName + "\\" + version.FileName))
                        {
                          File.WriteAllText(fi.DirectoryName + "\\" + version.FileName, "11");
                        }

                        foreach (Attachment att in version.Attachments)
                        {
                          if (!File.Exists(fi.DirectoryName + "\\" + att.FileName))
                          {
                            File.WriteAllText(fi.DirectoryName + "\\" + att.FileName, "11");
                          }

                        }


                      }
                    }
                  }
                }
              }
            }
          }


        }

        void EnumAndCreateSites(SharePoint.ImportExport.Core.Site Site, String DirectoryName)
        {
            string dir = Directory.GetCurrentDirectory();
            foreach (SharePoint.ImportExport.Core.Site subSite in Site.SubSites)
            {
                Directory.CreateDirectory(subSite.Name);
                EnumAndCreateSites(subSite, DirectoryName);
                Directory.SetCurrentDirectory(dir);
            }

            foreach (List List in Site.Lists)
            {
              if (File.Exists(DirectoryName + List.RelativeitemXML))
              {
                EnumAndCreateListItems(List, DirectoryName);
                continue;
              }
              else
              {
                Directory.CreateDirectory(DirectoryName + List.RelativeitemXML.Substring(0, List.RelativeitemXML.LastIndexOf("\\")));

                ListOfItems list = new ListOfItems();
                int id = 0;
                foreach (string template in List.Template.Split("#;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                {

                  ItemType it = new ItemType();
                  it.Name = template;
                  if (String.Compare(template, "folder", true) > 0)
                  {
                    string filename = DirectoryName + List.RelativeitemXML.Substring(0, List.RelativeitemXML.LastIndexOf("\\")) + "\\test" + id.ToString() + ".txt";
                    using (FileStream fs = new FileStream(filename, FileMode.Create))
                    {
                      using (StreamWriter sw = new StreamWriter(fs))
                      {
                        sw.WriteLine("Test");
                        sw.Flush();
                        sw.Close();
                      }
                    }


                    FileInfo fi = new FileInfo(filename);
                    Item item = new Item();
                    item.FileName = fi.Name;
                    item.DisplayName = fi.Name;
                    item.Fields.Add(new ItemProperty("Title", FieldType.Text, fi.Name));
                    item.Fields.Add(new ItemProperty("Editor", FieldType.User, "EUROPE\\kimforss"));
                    item.Fields.Add(new ItemProperty("Author", FieldType.User, "EUROPE\\kimforss"));
                    item.Fields.Add(new ItemProperty("Created", FieldType.DateTime, DateTime.Now.AddDays(-2).ToString()));
                    item.Fields.Add(new ItemProperty("Modified", FieldType.DateTime, DateTime.Now.AddDays(-1).ToString()));
                    it.Items.Add(item);
                  }
                  list.ItemTypes.Add(it);
                  id = id + 1;
                }
                list.Serialize(DirectoryName + List.RelativeitemXML);
              }
            }
         
        }

        void EnumSites(SharePoint.ImportExport.Core.Site Site, String DirectoryName)
        {
            foreach (SharePoint.ImportExport.Core.Site subSite in Site.SubSites)
            {
                EnumSites(subSite, DirectoryName);
            }
            foreach (List List in Site.Lists)
            {
                if (!File.Exists(DirectoryName + List.RelativeitemXML))
                    continue;

                // A FileStream is needed to read the XML document.
                FileStream fs = new FileStream(DirectoryName + List.RelativeitemXML, FileMode.Open);
                FileInfo fi=new FileInfo(DirectoryName + List.RelativeitemXML);
                // Declare an object variable of the type to be deserialized.
                SharePoint.ImportExport.Core.ListOfItems exportedList = new SharePoint.ImportExport.Core.ListOfItems();

                XmlReader reader = new XmlTextReader(fs);
                try
                {
                    // Create an instance of the XmlSerializer specifying type and namespace.
                    XmlSerializer serializer = new XmlSerializer(typeof(SharePoint.ImportExport.Core.ListOfItems));
                    // Use the Deserialize method to restore the object's state.
                    exportedList = (SharePoint.ImportExport.Core.ListOfItems)serializer.Deserialize(reader);
                    foreach (SharePoint.ImportExport.Core.ItemType profile  in exportedList.ItemTypes)
                    {

                        foreach (SharePoint.ImportExport.Core.Item item in profile.Items)
                        {
                            if (item.FileName != null)
                            {
                                if(!File.Exists(fi.DirectoryName+"\\"+item.FileName))
                                {
                                    File.WriteAllText(fi.DirectoryName + "\\" + item.FileName,"Empty");

                                }
                            }
                        }
                    }
                    

                }
                catch (Exception Ex)
                {
                }
                finally
                {
                    reader.Close();
                    fs.Close();

                }
            }
        }
        private void populateToolStripMenuItem_Click(object sender, EventArgs e)
        {
           FileInfo fi = new FileInfo(txtDataFile.Text);

           Directory.SetCurrentDirectory(fi.DirectoryName);
           foreach (Root rc in importStructure.RootContainers)
           {
               foreach (SharePoint.ImportExport.Core.Site Site in rc.Sites)
               {
                   EnumAndCreateSites(Site, fi.DirectoryName);
               }
           }


        }

        private void importToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void addListFromXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewStruct.SelectedNode;
            if (null != node)
            {
                if (node.Tag != null)
                {

                    SharePoint.ImportExport.Core.Site parentSite = null;
                    switch (node.Tag.GetType().ToString())
                    {
                        case "SharePoint.ImportExport.Core.Site":
                            {
                                parentSite = (SharePoint.ImportExport.Core.Site)node.Tag;
                                FileInfo fi = new FileInfo(this.txtDataFile.Text);
                                frmCreateListFromXml frm = new frmCreateListFromXml(fi.DirectoryName,parentSite );

                                if (DialogResult.OK == frm.ShowDialog())
                                {
                                    SaveStruct(false);
                                    LoadData(txtDataFile.Text);                                    
                                }
                                break;
                            }
                    }

                }
            }
        }

 
    }
}
